async function fetchInfo(name) {
  let url = "https://api.github.com/users/" + name;
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error("Error:", error);
  }
}

async function fetchRepo(name) {
  let url = `https://api.github.com/users/${name}/repos?sort=created`;
  try {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error("Error:", error);
  }
}

// fetchInfo("wesbos");
// fetchRepo("wesbos");
let profile = document.querySelector(".profile");
let searchBar = document.querySelector(".search");
let nameDiv = document.querySelector(".name");
let avatar = document.querySelector("img");
let bio = document.querySelector(".bio");
let f1 = document.querySelector(".num1");
let f2 = document.querySelector(".num2");
let f3 = document.querySelector(".num3");
let repos = document.querySelector(".repos");
// 添加keydown事件监听器

searchBar.addEventListener("keydown", async function (event) {
  // 检查按下的键是否是回车键
  if (event.key === "Enter") {
    let name = searchBar.value;
    let info = await fetchInfo(name);
    let repo = await fetchRepo(name);
    profile.style.display = "flex";
    avatar.src = info.avatar_url;
    console.log(info.name);
    nameDiv.textContent = info.name === null ? "xxx" : info.name;
    bio.textContent = info.bio === null ? "xxx" : info.bio;
    f1.textContent = info.followers;
    f2.textContent = info.following;
    f3.textContent = info.public_repos;
    let len = repo.length;
    len = len > 5 ? 5 : len;
    for (let i = 0; i < len; i++) {
      // 创建一个新的div元素
      var newDiv = document.createElement("div");
      // 创建一个新的a元素
      var newA = document.createElement("a");
      // 设置a元素的href属性和文本内容
      newA.href = repo[i].html_url;
      newA.textContent = repo[i].name;
      newDiv.classList.add("repo");
      // 将a元素添加到div中
      newDiv.appendChild(newA);

      // 将div元素添加到body中
      repos.appendChild(newDiv);
    }
  }
});
